package com.naizhuai.ui.mianbusiness.setting;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.naizhuai.MainActivity;
import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.R;
import com.naizhuai.network.exception.ApiException;
import com.naizhuai.ui.adapter.ChosenChargeJoinAdapterHolder;
import com.naizhuai.ui.adapter.ThankChosenUserAdapterHolder;
import com.naizhuai.ui.adapter.management.UserAbilityAdapter;
import com.naizhuai.ui.components.CircleImageView;
import com.naizhuai.ui.components.LabelsView;
import com.naizhuai.ui.components.RadarData;
import com.naizhuai.ui.components.RadarView;
import com.naizhuai.ui.components.SingleLabelsView;
import com.naizhuai.ui.components.swipeback.SwipeBackActivity;
import com.naizhuai.ui.entity.ChargeCheckItemBean;
import com.naizhuai.ui.entity.StartUp;
import com.naizhuai.ui.entity.VirtualChosenBean;
import com.naizhuai.ui.entity.mainbusiness.ActionSubmitScanDetailsBean;
import com.naizhuai.ui.entity.setting.UserAbilityLabels;
import com.naizhuai.ui.entity.setting.UserRadarLabels;
import com.naizhuai.ui.mianbusiness.action.ActionScanDetailsViewActivity;
import com.naizhuai.ui.mianbusiness.action.presenter.ActionManageApiStoreIml;
import com.naizhuai.ui.mianbusiness.setting.presenter.UserPersonalApiStoreIml;
import com.naizhuai.util.ActivityStackManager;
import com.naizhuai.util.ConstantsState;
import com.naizhuai.util.DialogUtils;
import com.naizhuai.util.ImageUtils;
import com.naizhuai.util.IntentUtils;
import com.naizhuai.util.ListUtils;
import com.naizhuai.util.NaizhuAILog;
import com.naizhuai.util.UidUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observer;
import rx.Subscription;

/**
 * 行为感谢卡设置界面
 */
public class ThankSettingPagerActivity extends SwipeBackActivity implements View.OnClickListener, ThankChosenUserAdapterHolder.OnItemClickListener, TextWatcher {
    private static final String TAG = "ThankSettingPagerActivity";
    public static final String SUBMIT_MAP_KEY = "submit_msg_key";


    @BindView(R.id.chosen_thank_user_list)
    RecyclerView thankListView;
    private ThankChosenUserAdapterHolder thankAdapter;
    private List<PersonUserBean> chosenBeans;

    public static final int CHOSEN_THANK_USERS = 2001;

    public static final String TOTAL_WORD_LIMITED = "30";

    @BindView(R.id.img_type_1)
    ImageView imgType1;
    @BindView(R.id.img_type_check_1)
    ImageView check1;
    @BindView(R.id.img_type_2)
    ImageView imgType2;
    @BindView(R.id.img_type_check_2)
    ImageView check2;

    @BindView(R.id.thank_txt)
    EditText thankTxt;
    @BindView(R.id.number_show)
    TextView numberTxt;
    private String numberShowStr;

    private int selectedStyle = -1;

    private ActionSubmitScanDetailsBean submitBean;

    private Subscription submitSub;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBasicData();
        initBaseTypeView();
    }

    private void initBasicData() {
        chosenBeans = new ArrayList<>();
        numberShowStr = getString(R.string.thank_number_show);
        numberTxt.setText(String.format(numberShowStr, thankTxt.getText().length(), TOTAL_WORD_LIMITED));
        submitBean = (ActionSubmitScanDetailsBean) getIntent().getSerializableExtra(SUBMIT_MAP_KEY);
        if (submitBean == null) {
            shortToast(getString(R.string.get_message_error));
            finish();
        }
    }

    private void initBaseTypeView() {
        imgType1.post(new Runnable() {
            @Override
            public void run() {
                int imgWidth = imgType1.getWidth();
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imgType1.getLayoutParams();
                params.height = imgWidth / 16 * 9;
                imgType1.setLayoutParams(params);
                imgType2.post(new Runnable() {
                    @Override
                    public void run() {
                        int imgWidth = imgType2.getWidth();
                        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imgType2.getLayoutParams();
                        params.height = imgWidth / 16 * 9;
                        imgType2.setLayoutParams(params);
                        initBaseView();
                    }
                });
            }
        });
    }

    private void initBaseView() {
        //需要选择的感谢信的样式
        ImageUtils.glideImageViewByUrl(this, imgType1, getShareValue(StartUp.THANK_CARD_SHOW_IMG + 0, ""));
        ImageUtils.glideImageViewByUrl(this, imgType2, getShareValue(StartUp.THANK_CARD_SHOW_IMG + 1, ""));

        //选择的感谢人横向列表
        thankAdapter = new ThankChosenUserAdapterHolder(this, chosenBeans);
        thankListView.setNestedScrollingEnabled(false);
        thankListView.setHasFixedSize(true);
        thankListView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        thankListView.setItemAnimator(new DefaultItemAnimator());
        thankListView.setAdapter(thankAdapter);
        thankAdapter.setOnItemClickListener(this);
        thankTxt.addTextChangedListener(this);
    }


    @OnClick({R.id.base_back_icon, R.id.img_type_1, R.id.img_type_2, R.id.submit_thank})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.base_back_icon:
                super.onBackPressed();
                break;
            case R.id.img_type_1:
                if (check1.isSelected())
                    selectedStyle = -1;
                else
                    selectedStyle = 0;
                check1.setSelected(!check1.isSelected());
                check2.setSelected(false);
                break;
            case R.id.img_type_2:
                if (check2.isSelected())
                    selectedStyle = -1;
                else
                    selectedStyle = 1;
                check2.setSelected(!check2.isSelected());
                check1.setSelected(false);
                break;
            case R.id.submit_thank:
                if (selectedStyle == -1) {
                    DialogUtils.showPromptDialog(this, getString(R.string.chosen_thank_style_error));
                    return;
                }
                if (TextUtils.isEmpty(thankTxt.getText().toString())) {
                    DialogUtils.showPromptDialog(this, getString(R.string.chosen_thank_content_error));
                    return;
                }
                if (chosenBeans.size() < 1) {
                    DialogUtils.showPromptDialog(this, getString(R.string.chosen_thank_user_error));
                    return;
                }
                ActionSubmitScanDetailsBean.ThankData thankData = new ActionSubmitScanDetailsBean.ThankData();
                String style = selectedStyle == 0 ? getShareValue(StartUp.THANK_CARD_SELECTED_IMG + selectedStyle, "") : getShareValue(StartUp.THANK_CARD_SELECTED_IMG + selectedStyle, "");
                thankData.setStyle(style);
                thankData.setContent(thankTxt.getText().toString());
                List<String> chosenIds = new ArrayList<>();
                for (PersonUserBean userBean : chosenBeans) {
                    chosenIds.add(userBean.getUid());
                }
                thankData.setThanksUid(new UidUtil(chosenIds).toString());
                submitBean.setThankData(thankData);
                postActionScanDetailsData();
                break;
        }
    }

    private void postActionScanDetailsData() {
        Map<String, String> detailsMap = new HashMap<>();
        detailsMap.put(ActionSubmitScanDetailsBean.QUESTION_ID_KEY, submitBean.getQuestionId());
        detailsMap.put(ActionSubmitScanDetailsBean.REVIEW_KEY, submitBean.getReview());
        NaizhuAILog.e("getReview=" + submitBean.getReview());
        detailsMap.put(ActionSubmitScanDetailsBean.CHANGE_DATA_KEY, submitBean.getChangeData());
        NaizhuAILog.e("getChangeData=" + submitBean.getChangeData());
        detailsMap.put(ActionSubmitScanDetailsBean.CHANGE_IMAGE_KEY, submitBean.getChangeImages());
        NaizhuAILog.e("getChangeImages=" + submitBean.getChangeImages());

        detailsMap.put(ActionSubmitScanDetailsBean.THANK_DATA_KEY, submitBean.getThankData());
        NaizhuAILog.e("getThankData=" + submitBean.getThankData());

        submitSub = ActionManageApiStoreIml.getInstance().submitActionDetails(detailsMap).subscribe(submitObser);
        showWaitDiaLog(submitSub);
    }

    private Observer<String> submitObser = new Observer<String>() {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            hideWaitDialog();
            NaizhuAILog.e("postActionScanDetailsData_Throwable e=" + e.getMessage());
            ApiException.showException(e, getActivityContext(), true);
        }

        @Override
        public void onNext(String s) {
            hideWaitDialog();
            if (ConstantsState.isResultOk(s)) {
                shortToast("提交成功");
                IntentUtils.startActivity(getActivityContext(), MainActivity.class);
//                ActivityStackManager.getInstance().killAllActivityExceptOne(MainActivity.class);
            } else
                shortToast("提交失败");
        }
    };

    @Override
    public void onBackPressedWithoutDialog() {
        DialogUtils.showSureDialog(this, getString(R.string.lost_data), dialog -> finish());
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_thank_setting_layout;
    }

    @Override
    public void onItemClick(View view, int position, int clickType) {
        switch (clickType) {
            case ThankChosenUserAdapterHolder.TYPE_CLICK_DETAILS:
                chosenBeans.remove(position);
                thankAdapter.notifyDataSetChanged();
                break;
            case ThankChosenUserAdapterHolder.TYPE_CLICK_ADD:
                IntentUtils.startActivityWithStringForResult(new String[]{ChosenChargeJoinAdapterHolder.ENTER_TYPE_KEY},
                        new int[]{ChosenChargeJoinAdapterHolder.TYPE_THANKS_PERSON}, this, UserListChosenActivity.class, CHOSEN_THANK_USERS);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null)
            return;
        List<PersonUserBean> users = (List<PersonUserBean>) data.getSerializableExtra(UserListChosenActivity.JOIN_PERSON_KEY);
        switch (requestCode) {
            case CHOSEN_THANK_USERS:
                List<PersonUserBean> diffBean = ListUtils.getListsDifferData(chosenBeans, users);
                if (ListUtils.contain(diffBean, getShareValue(PersonUserBean.USER_ID_KEY, ""))) {
                    DialogUtils.showPromptDialog(this, getString(R.string.thank_number_error));
                    diffBean = ListUtils.removeElement(diffBean, getShareValue(PersonUserBean.USER_ID_KEY, ""));
                }
                chosenBeans.addAll(diffBean);
                thankAdapter.notifyDataSetChanged();
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        numberTxt.setText(String.format(numberShowStr, s.length(), TOTAL_WORD_LIMITED));
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
